<template>
  <a-spin :spinning="spinning" :tip="spinningMessage">
    <div class="form-container">
      <a-collapse v-model="collapseActiveKey">
        <!-- 基本信息设置 -->
        <a-collapse-panel key="1" header="基本信息">
          <!-- 数据类型 button-group -->
          <data-type-tab
            :selected-data-type="selectedDataType"
            @change="selectedDataTypeChange"
          />
          <!-- 不同数据类型 表单 -->
          <component
            :is="getFormCompType(selectedDataType)"
            ref="currentForm"
            :data-images="dataImages"
            @form-set-selected-keys="emitSetSelectedKeys"
            @begin-database-upload="emitBeginDatabaseUpload"
          />
        </a-collapse-panel>

        <!-- 高级配置 -->
        <a-collapse-panel
          v-if="advancedSettingsCollapsePanelShow"
          key="2"
          header="高级设置"
        >
          <advanced-setting
            @confirm-advanced-setting="confirmAdvancedSetting"
          />
        </a-collapse-panel>

        <!-- 数据信息 - 数据导入配置 -->
        <a-collapse-panel
          v-if="dataInformationCollapsePanelShow"
          key="3"
          header="数据信息"
        >
          <!-- 脱敏设置 -->
          <data-info-setting
            v-if="availableConfigurationItems.config"
            :selected-data-type="selectedDataType"
            :available-configuration-items="availableConfigurationItems"
            @toggle-type-semantic-infer="toggleTypeSemanticInfer"
            @desensitization-setting="emitDesensitizationSetting"
            @timing-setting="emitTimingSetting"
          />
          <!-- 不同数据类型 数据预览 -->
          <component
            :is="getPreviewCompType(selectedDataType)"
            ref="currentPreviewCom"
            :selected-data-type="selectedDataType"
          />
          <!-- 取消/ 确认 -->
          <div class="confirm-cancel-button">
            <a-button @click="cancelImportData">取消</a-button>
            <!-- 确认导入数据 新用户引导 step-4 -->
            <guide-step-popover :guide-step="4">
              <template #header>
                <a-button type="primary" class="button" @click="handleSubmit"
                  >确定
                </a-button>
              </template>
            </guide-step-popover>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </a-spin>
</template>
<script lang="ts">
/**
 * 数据上传主页面
 * @author Jinhui Hou
 */
import { Component, Vue } from 'vue-property-decorator'
import GuideStepPopover from '@/components/user-guide/GuideStepPopover.vue'
import DataUploadStore from '@/store/modules/data-upload'
// 数据类型 button
import DataTypeTab from '@/components/data/basic-information/DataTypeTab.vue'
// 表格文件 form
import TableDataForm from '@/components/data/basic-information/TableDataForm.vue'
// 数据库 form
import DatabaseDataForm from '@/components/data/basic-information/DatabaseDataForm.vue'
// 图文件 form
import GraphDataForm from '@/components/data/basic-information/GraphDataForm.vue'
// http 数据 form
import HttpDataForm from '@/components/data/basic-information/HttpDataForm.vue'
// 图谱文件 form
import KGraphDataForm from '@/components/data/basic-information/KGraphDataForm.vue'
// GIS 数据 form
import GisDataForm from '@/components/data/basic-information/GisDataForm.vue'
// 高级配置
import AdvancedSetting from '@/components/data/advanced-settings/AdvancedSetting.vue'
// 脱敏设置
import DataInfoSetting from '@/components/data/data-information/setting/DataInfoSetting.vue'

// 图数据预览
import GraphDataPreview from '@/components/data/data-information/GraphDataPreview.vue'
// 表数据预览
import TableDataPreview from '@/components/data/data-information/TableDataPreview.vue'
// 数据库预览
import DatabaseDataPreview from '@/components/data/data-information/DatabaseDataPreview.vue'
// http 数据预览
import HttpDataPreview from '@/components/data/data-information/HttpDataPreview.vue'
// Gis 数据预览
import GisDataPreview from '@/components/data/data-information/GisDataPreview.vue'
// kg 数据预览
import KGraphDataPreview from '@/components/data/data-information/KGraphDataPreview.vue'

import { settingMap } from '@/components/data/data-import-com-config'
import { setLocalStorage, getLocalStorage } from '@/util/util'

interface KeyValue {
  [key: string]: any
}
// 数据类型
type UploadDataType = 'table' | 'database' | 'graph' | 'http' | 'gis'

// 不同数据类型表单组件
const formCompMaps: any = {
  table: 'table-data-form',
  database: 'database-data-form',
  graph: 'graph-data-form',
  http: 'http-data-form',
  gis: 'gis-data-form',
  k_graph: 'k-graph-data-form',
}
// 不同数据类型预览组件
const previewCompMaps: any = {
  table: 'table-data-preview',
  database: 'database-data-preview',
  graph: 'graph-data-preview',
  http: 'http-data-preview',
  gis: 'gis-data-preview',
  k_graph: 'k-graph-data-preview',
}

@Component({
  components: {
    GuideStepPopover,
    DataTypeTab,
    TableDataForm,
    DatabaseDataForm,
    GraphDataForm,
    HttpDataForm,
    KGraphDataForm,
    GisDataForm,
    AdvancedSetting,
    DataInfoSetting,
    GraphDataPreview,
    TableDataPreview,
    DatabaseDataPreview,
    HttpDataPreview,
    GisDataPreview,
    KGraphDataPreview,
  },
})
export default class DataUploadIndex extends Vue {
  // 折叠面板相关参数
  private collapseActiveKey: Array<string> = ['1', '2', '3', '4']
  // 数据类型
  private selectedDataType: UploadDataType = 'table'
  // 数据源（包含图片）mysql / oracle / rds-mysql / json
  private dataImages: any = []

  public get spinning(): boolean {
    return DataUploadStore.spinning
  }
  public get spinningMessage(): string {
    return DataUploadStore.spinningMessage || '请等待...'
  }

  // 高级设置 show
  public get advancedSettingsCollapsePanelShow() {
    return DataUploadStore.advancedSettingsCollapsePanelShow
  }

  // 数据信息 show
  public get dataInformationCollapsePanelShow() {
    return DataUploadStore.dataInformationCollapsePanelShow
  }

  public get availableConfigurationItems() {
    return settingMap[this.selectedDataType]
  }

  // 不同数据类型表单组件
  public getFormCompType(type: string): string {
    const result = 'table-data-form'
    if (formCompMaps[type]) {
      return formCompMaps[type]
    }
    return result
  }

  // 不同数据类型预览组件
  public getPreviewCompType(type: string): string {
    const result = 'table-data-preview'
    if (previewCompMaps[type]) {
      return previewCompMaps[type]
    }
    return result
  }

  public created() {
    this.getDatabaseTypeImg()
    const lastUrlStorage: any = sessionStorage.getItem('lastUrl')
    if (lastUrlStorage !== undefined && lastUrlStorage !== null) {
      const { loadType } = JSON.parse(lastUrlStorage)
      this.selectedDataType = loadType
      setLocalStorage('selectedDataType', loadType)
    } else {
      const selectedDataType: any = getLocalStorage('selectedDataType')
      if (
        ['table', 'database', 'graph', 'http', 'gis'].includes(selectedDataType)
      ) {
        this.selectedDataType = selectedDataType
      } else {
        setLocalStorage('selectedDataType', 'table')
        this.selectedDataType = 'table'
      }
    }
  }

  public mounted() {
    this.initUpdateDataStore()
  }

  /**
   * 初始化仓库
   */
  public initUpdateDataStore() {
    DataUploadStore.initStore()
  }

  /**
   * 获取图片
   */
  public getDatabaseTypeImg() {
    const response = DataUploadStore.getDatabaseTypeImg({ type: null })
    response.then((result: any) => {
      this.dataImages = result.result
    })
  }

  /**
   * 切换数据导入的文件类型
   */
  public selectedDataTypeChange(value: UploadDataType) {
    this.selectedDataType = value
    setLocalStorage('selectedDataType', value)
    DataUploadStore.setAdvancedSettingsCollapsePanelShow(false)
    DataUploadStore.setDataInformationCollapsePanelShow(false)
    DataUploadStore.initSeparateQuoteEscape() // 初始化高级配置
  }

  /**
   * 切换是否使用推断类型/语义
   */
  public toggleTypeSemanticInfer(info: {
    type: 'type' | 'semantic'
    value: boolean
  }) {
    const currentPreviewCom: any = this.$refs.currentPreviewCom as Vue
    if (
      currentPreviewCom &&
      typeof currentPreviewCom.toggleTypeSemanticInfer === 'function'
    ) {
      currentPreviewCom.toggleTypeSemanticInfer(info)
    }
  }

  /**
   * 脱敏设置 确认 （上传信息的表单和预览表单触发事件）
   * @private
   */
  private emitDesensitizationSetting() {
    const currentForm: any = this.$refs.currentForm as Vue
    if (
      currentForm &&
      typeof currentForm.importAndDesensitizationTriggeringEvent === 'function'
    ) {
      currentForm.importAndDesensitizationTriggeringEvent()
    }
    const currentPreviewCom: any = this.$refs.currentPreviewCom as Vue
    if (
      currentPreviewCom &&
      typeof currentPreviewCom.importAndDesensitizationTriggeringEvent ===
        'function'
    ) {
      currentPreviewCom.importAndDesensitizationTriggeringEvent()
    }
  }

  /**
   * 定时配置更改
   * todo 是否触发其他组件事件
   */
  public emitTimingSetting() {}

  /**
   * 取消上传 (是回到视图页面)
   */
  public cancelImportData() {
    this.cancelUploadClearInfo() // 清除数据 和 状态

    let lastUrl: any = sessionStorage.getItem('lastUrl')
    // 跳转回视图页面 数据视图 / 时空分析 / 多源异构
    if (lastUrl !== undefined && lastUrl !== null) {
      lastUrl = JSON.parse(lastUrl)
      const { href } = this.$router.resolve({
        path: lastUrl.url,
      })
      window.location.href = href
      sessionStorage.removeItem('lastUrl')
    } else {
      // TODO 正常的进入数据页面 导入取消
      // const lastId =
      //   DataStore.preSelectedDataset.length > 0
      //     ? DataStore.preSelectedDataset.slice(-1)[0].id
      //     : -1
      // DataStore.cancelImport()
      // DataStore.setSelectedDatasetId(lastId)
      this.$router.push('/management/data')
      // 在 用户引导状态下 预览数据， 取消导入， 提示步骤回到 step-2
      // this.updateDataSuccessToGuideStep(2)
    }
  }

  /**
   * 取消上传后处理的事情
   */
  public cancelUploadClearInfo() {
    DataUploadStore.setAdvancedSettingsCollapsePanelShow(false) // 高级配置折叠面板关闭
    DataUploadStore.setDataInformationCollapsePanelShow(false) // 数据信息折叠面板关闭

    const currentForm: any = this.$refs.currentForm as Vue
    if (currentForm && typeof currentForm.cancelImportData === 'function') {
      currentForm.cancelImportData()
    }
  }

  /**
   * 点击 确定 button 提交数据
   */
  public handleSubmit(event: Event) {
    event.preventDefault()
    const currentForm: any = this.$refs.currentForm as Vue
    if (currentForm && typeof currentForm.handleSubmit === 'function') {
      currentForm.handleSubmit()
    }
  }

  /**
   * 上传完成 预览
   */
  public emitSetSelectedKeys(keys: string[]) {
    this.$emit('set-selected-keys', keys)
  }

  /**
   * 数据库导入
   * @param passData
   */
  public emitBeginDatabaseUpload(passData: any) {
    this.$emit('begin-database-upload', passData)
  }

  /**
   * 高级设置后， 重新上传文件
   */
  public confirmAdvancedSetting() {
    const currentForm: any = this.$refs.currentForm as Vue
    if (
      currentForm &&
      typeof currentForm.advancedSettingTriggeringEvent === 'function'
    ) {
      currentForm.advancedSettingTriggeringEvent()
    }
  }
}
</script>
<style lang="less" scoped>
// 重新定义 antdvue loading
/deep/.ant-spin-nested-loading {
  height: 100%;

  > div:first-child {
    height: 100%;
  }
}

/deep/.ant-spin-spinning {
  max-height: none;
}

.form-container {
  height: 100%;
  min-width: 800px;
  overflow-y: auto;
  padding: 26px 24px 0;
  position: relative;

  .upload-data-spinning {
    align-items: center;
    //background-color: rgba(87, 96, 230, 0.1);
    display: flex;
    height: 100%;
    justify-content: center;
    left: 0;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 100;
  }

  .confirm-cancel-button {
    align-items: center;
    display: flex;
    flex-direction: row;
    justify-content: center;
    padding: 20px 0 10px;
    width: 100%;

    button {
      margin-right: 10px;
    }

    .button {
      background-color: #6973ff;
    }
  }
}

.ant-form-model {
  margin-top: 46px;
}

//折叠面板样式
/deep/ .ant-collapse {
  background: #fff;
  border: 0 solid #fff;

  .ant-collapse-item {
    border-bottom: 0 solid #fff;
    margin-bottom: 24px;
  }

  .ant-collapse-header {
    background: rgba(233, 233, 233, 0.2);
    border: 1px solid #e9e9e9;
    color: #373b52;
    font-size: 14px;
    font-weight: 600;
    height: 36px;
    letter-spacing: 1px;
    line-height: 36px;
    padding-bottom: 0;
    padding-top: 0;
  }

  .ant-collapse-content {
    border: 1px solid #e9e9e9;
    border-top: 0 solid #e9e9e9;

    .ant-collapse-content-box {
      overflow-x: auto;
      padding-left: 25px;
      width: 100%;

      &::-webkit-scrollbar {
        height: 6px;
        width: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(144, 147, 153, 0.5);
        border-radius: 6px;
      }

      &::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 5px;
      }
    }
  }
}
</style>
